" 注意 "mapleader" 的值仅当定义映射时被使用。后来改变的 "mapleader" 不会影响已定义的映射。
let mapleader=";"

" 判断操作系统
if(has("win32") || has("win95") || has("win64") || has("win16") || has("win32unix")) "判定当前操作系统类型
    let g:iswindows=1
else
    let g:iswindows=0
endif
" 判断是终端还是gvim
if has("gui_running")
    let g:isGUI = 1
else
    let g:isGUI = 0
endif

" =========================== Vundle Configure Begin ===========================
" Sun Jun 26 09:40:01 CST 2016

"" 1) Set up Vundle:
"   $ mkdir -p .vim/bundle/Vundle.vim
"   $ git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
"" 2) Configure Plugins:
"   Put this at the top of your .vimrc to use Vundle. Remove plugins you don't need

set nocompatible              " be iMproved, required
filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim

call vundle#begin()
    " alternatively, pass a path where Vundle should install plugins
    "call vundle#begin('~/some/path/here')

    " let Vundle manage Vundle, required
    Plugin 'VundleVim/Vundle.vim'

    " The following are examples of different formats supported.
    " Keep Plugin commands between vundle#begin/end.

    " 1) plugin on GitHub repo
    Plugin 'kien/tabman.vim'            " a convenient way to navigate between tabs and the windows they contain
    "Plugin 'michaeljsmith/vim-indent-object' " defines a new text object, based on indentation levels
    "Plugin 'zirrostig/vim-schlepp' " allow the movement of lines (or blocks) of text around easily

    Plugin 'luochen1990/rainbow'   " 彩虹括号增强版 (Rainbow Parentheses Improved)
    let g:rainbow_active = 1
    let g:rainbow_conf = {
        \    'guifgs': ['White', 'darkorange3', 'royalblue3', 'seagreen3', 'LightMagenta', 'SlateBlue', 'firebrick', 'Yellow'],
        \    'ctermfgs': ['White','Brown','DarkBlue','DarkGreen','DarkCyan','DarkMagenta','DarkRed','Yellow'],
        \}

    " bug fix: centos 6中默认安装的 vim 7会出现卡顿的情况
    if v:version >= 900
        Plugin 'Yggdroot/indentLine'        " vim plugin to display the indention levels with thin vertical lines
            map <leader>il :IndentLinesToggle<CR>
            "let g:indentLine_char = '│'
            let g:indentLine_enabled = 1 " Disable by default
            let g:indentLine_indentLevel = 200
            " Vim
            let g:indentLine_color_term = 239
            " GVim
            let g:indentLine_color_gui = '#A4E57E'
            " none X terminal
            let g:indentLine_color_tty_light = 7 " (default: 4)
            let g:indentLine_color_dark = 1 " (default: 2)
    endif
    Plugin 'clwu88/DBGPavim'            " clwu fix 转义 双引号  An improved PHP debugger

    Plugin 'ludovicchabant/vim-gutentags'
        " TODO: gutentags_gtags_executable 目前只能支持php，其它语言要手工切换回 ctags gtags
        " let g:gutentags_gtags_executable = vundle#bundle_dir.'/vim_misc_tools/phpctags.phar'
        " let g:gutentags_ctags_extra_args = [ '--fields=+afmikKlnsStz' ]

        " let g:gutentags_ctags_exclude    = ['*.css', '*.html', '*.js', '*.log', '*.ini', '*.xml', '*.json', 'node_modules', 'vendor']
        let g:gutentags_cache_dir          = '~/.vim/.cache/gutentags'

        " gutentags 搜索工程目录的标志，当前文件路径向上递归直到碰到这些文件/目录名
        let g:gutentags_project_root = ['.root', '.svn', '.git', '.hg', '.project']
        " 所生成的数据文件的名称
        let g:gutentags_ctags_tagfile = '.tags'

        " 同时开启 ctags 和 gtags 支持：
        let g:gutentags_modules = []
        " 还是使用 universal-ctags 默认就已经很好支持 php
        if executable('ctags')
            let g:gutentags_modules += ['ctags']
        endif
        " cscope 项目已经不维护了，改用 GNU global中的 gtags-cscope
        " -a     Print absolute path names
        let g:gutentags_gtags_cscope_executable = 'gtags-cscope -a'
        if executable('gtags-cscope') && executable('gtags')
            let g:gutentags_modules += ['gtags_cscope']
            set cscopeprg=gtags-cscope
        endif
        " 禁用 gutentags 自动加载 gtags 数据库的行为
        " let g:gutentags_auto_add_gtags_cscope = 0

        " 配置 ctags 的参数，老的 Exuberant-ctags 不能有 --extra=+q，注意
        " let g:gutentags_ctags_extra_args = ['--fields=+niazS', '--extra=+q']
        " let g:gutentags_ctags_extra_args += ['--c++-kinds=+px']
        " let g:gutentags_ctags_extra_args += ['--c-kinds=+px']
        " 如果使用 universal ctags 需要增加下面一行，老的 Exuberant-ctags 不能加下一行
        " let g:gutentags_ctags_extra_args += ['--output-format=e-ctags']

        if !isdirectory(g:gutentags_cache_dir)
            silent! call mkdir(s:vim_tags, 'p')
        endif
        map <silent> <leader>jd :CtrlPTag

    if v:version >= 800
        " it provides linting for Vim 8
        Plugin 'dense-analysis/ale'
        let g:ale_linters = {
            \   'php': ['php'],
            \}
        let g:ale_lint_on_save = 1
        let g:ale_lint_on_text_changed = 0
    endif

    " vim 8 之后已经可以在vim内打开终端使用gdb
    if v:version < 800
        " if globpath( substitute($PATH, ':', ',', 'g'), 'python3' ) != '' " if you had install python3
        if has('python3')
            " ################ for python3 >= 3.4 ###############
            let $PYTHONPATH .= vundle#bundle_dir.'/vim_pyclewn/usr/lib64/python3.4/site-packages' " search path for module files
            let g:pyclewn_python = 'python3'    " python3 version must >= 3.4
        else
            " ################ for python2.7 ####################
            let $PYTHONPATH .= vundle#bundle_dir.'/vim_pyclewn/usr/lib64/python2.7/site-packages' " search path for module files
        endif
        map <F9> :C continue <CR>
        map <F8> :C next <CR>
        map <F7> :C step <CR>
        map <S-F8> :C finih <CR>
        " map <C-c> :C sigint <CR> " kill the inferior running program
        Plugin 'clwu88/vim_pyclewn'         " Make pyclewn can be installed though vbundle
    endif

    " 解决tmux下vim颜色显示不正常的方法                                                                               
    " 在.bashrc中加入如下配置                                                                                         
    " alias tmux="TERM=screen-256color-bce tmux"                                                                      
    Plugin 'christoomey/vim-tmux-navigator'         " Seamless navigation between tmux panes and vim splits           
        let g:tmux_navigator_no_mappings = 1                                                                          
        nnoremap <silent> <c-t-h> :TmuxNavigateLeft<cr>                                                               
        nnoremap <silent> <c-t-j> :TmuxNavigateDown<cr>                                                               
        nnoremap <silent> <c-t-k> :TmuxNavigateUp<cr>                                                                 
        nnoremap <silent> <c-t-l> :TmuxNavigateRight<cr>                                                              
        nnoremap <silent> <c-t-\> :TmuxNavigatePrevious<cr>                                                           
        " Add the following to your ~/.tmux.conf file:                                                                
        "                                                                                                             
        " # Smart pane switching with awareness of Vim splits.                                                        
        " # See: https://github.com/christoomey/vim-tmux-navigator                                                    
        " is_vim="ps -o state= -o comm= -t '#{pane_tty}' \                                                            
        "     | grep -iqE '^[^TXZ ]+ +(\\S+\\/)?g?(view|n?vim?x?)(diff)?$'"                                           
        " bind-key -n C-h if-shell "$is_vim" "send-keys C-h"  "select-pane -L"                                        
        " bind-key -n C-j if-shell "$is_vim" "send-keys C-j"  "select-pane -D"                                        
        " bind-key -n C-k if-shell "$is_vim" "send-keys C-k"  "select-pane -U"                                        
        " bind-key -n C-l if-shell "$is_vim" "send-keys C-l"  "select-pane -R"                                        
        " bind-key -n C-\ if-shell "$is_vim" "send-keys C-\\" "select-pane -l"                                        
        " bind-key -T copy-mode-vi C-h select-pane -L                                                                 
        " bind-key -T copy-mode-vi C-j select-pane -D                                                                 
        " bind-key -T copy-mode-vi C-k select-pane -U                                                                 
        " bind-key -T copy-mode-vi C-l select-pane -R                                                                 
        " bind-key -T copy-mode-vi C-\ select-pane -l                                                                 
                                                                                                                      
    "Plugin 'python-mode/python-mode'        " Vim python-mode. PyLint, Rope, Pydoc, breakpoints from box. @see 中文帮助 http://blog.csdn.net/Demorngel/article/details/71158792
    "    let g:pymode_python = 'python3'     " 默认情况下， Python-mode 使用 Python 2 进行语法检查。你可以在 .vimrc 文件中加入下面这行内容从而启动 Python 3 语法检查。

    Plugin 'vim-scripts/SearchComplete' " Tab completion of words inside of a search ('/') 

    "Plugin 'vim-scripts/UltiSnips'      " 1) The ultimate snippet solution for python enabled Vim
        " 新版 UltiSnips 并未自带预定义的代码模板，你可以从 https://github.com/honza/vim-snippets 获取各类语言丰富的代码模板，也可以重新写一套符合自己编码风格的模板。
        " 默认情况下，UltiSnips 模板补全快捷键是 <tab>，与后面介绍的 YCM 快捷键有冲突，所有须在 .vimrc 中重新设定：
        let g:UltiSnipsExpandTrigger="<leader><tab>"
        let g:UltiSnipsJumpForwardTrigger="<leader><tab>"
        let g:UltiSnipsJumpBackwardTrigger="<leader><s-tab>"
    Plugin 'honza/vim-snippets'         " Snippets are separated from ultisnips

    "Plugin 'scrooloose/syntastic'       " 常用的语言的语法检测
        " :help syntastic-checkers
    Plugin 'gregsexton/gitv'        " gitk for Vim
    Plugin 'tpope/vim-fugitive'     " a Git wrapper https://github.com/tpope/vim-fugitive#screencasts
    Plugin 'tpope/vim-commentary'   " 批量注释工具, 可以注释多行和去除多行注释
    Plugin 'tpope/vim-abolish'      " http://vimcasts.org/episodes/supercharged-substitution-with-subvert/
    "Plugin 'tpope/vim-unimpaired'  " 一些不错的配置，可以让[]发挥奇效
        " :help commentary
        autocmd FileType python,shell set commentstring=#\ %s       " 设置Python注释字符
    Plugin 'easymotion/vim-easymotion'    " Vim motions on speed!
    Plugin 'terryma/vim-multiple-cursors' " True Sublime Text style multiple selections for Vim
    Plugin 'dkprice/vim-easygrep'         " Fast and Easy Find and Replace Across Multiple Files
    Plugin 'dyng/ctrlsf.vim'              " An ack.vim alternative mimics Ctrl-Shift-F on Sublime Text 2
        if g:iswindows
            let g:ctrlsf_ackprg             = vundle#bundle_dir.'/vim_misc_tools/windows_x64/rg.exe'
        else
            let g:ctrlsf_ackprg             = vundle#bundle_dir.'/vim_misc_tools/linux_x64/ripgrep/usr/bin/rg'
        endif
        let g:ctrlsf_auto_close         = 0
        let g:ctrlsf_confirm_save       = 0
        let g:ctrlsf_context            = '-C 5'
        let g:ctrlsf_absolute_file_path = 1
        let g:ctrlsf_default_root       = 'project'
        let g:ctrlsf_ignore_dir         = ['bower_components', 'npm_modules']
        " let g:ctrlsf_extra_backend_args = {
        "     \ 'ack': '--type=cc',  "@see ack --help=types
        "     \ 'rg':  '--type c',   "@see rg  --type-list
        "     \ }
        nmap <Leader><Leader>s <Plug>CtrlSFPrompt
        ""nmap     <C-s>f <Plug>CtrlSFPrompt
        "nmap     <C-F>f <Plug>CtrlSFPrompt // TODO 导致了 C-F 翻页的响应慢了
        "vmap     <C-F>f <Plug>CtrlSFVwordPath
        "vmap     <C-F>F <Plug>CtrlSFVwordExec
        "nmap     <C-F>n <Plug>CtrlSFCwordPath
        "nmap     <C-F>p <Plug>CtrlSFPwordPath
        "nnoremap <C-F>o :CtrlSFToggle<CR>
    Plugin 'ctrlpvim/ctrlp.vim'     " 1) Fuzzy file, buffer, mru, tag, etc finder
        let g:ctrlp_arg_map = 1
        "let g:ctrlp_extensions = ['undo', 'changes'] 
        let g:ctrlp_custom_ignore = {
            \ 'dir':  '\v[\/](doc|tmp|node_modules)',
            \ 'file': '\v\.(exe|so|dll|o|lo|orig)$',
            \ }
        let g:ctrlp_user_command = ['.git', 'cd %s && git ls-files']
    Plugin 'Shougo/unite.vim'       " 2) Unite and create user interfaces
    Plugin 'Shougo/neocomplete.vim' " completion framework
        if exists(":NeoCompleteEnable")
            " Disable AutoComplPop.
            let g:acp_enableAtStartup = 0
            " Use neocomplete.
            let g:neocomplete#enable_at_startup = 1
            " Use smartcase.
            let g:neocomplete#enable_smart_case = 1
            " Set minimum syntax keyword length.
            let g:neocomplete#sources#syntax#min_keyword_length = 3
            let g:neocomplete#lock_buffer_name_pattern = '\*ku\*'

            " Define dictionary.
            let g:neocomplete#sources#dictionary#dictionaries = {
                \ 'default' : '',
                \ 'vimshell' : $HOME.'/.vimshell_hist',
                \ 'scheme' : $HOME.'/.gosh_completions'
                    \ }

            " Define keyword.
            if !exists('g:neocomplete#keyword_patterns')
                let g:neocomplete#keyword_patterns = {}
            endif
            let g:neocomplete#keyword_patterns['default'] = '\h\w*'

            " Plugin key-mappings.
            inoremap <expr><C-g>     neocomplete#undo_completion()
            inoremap <expr><C-l>     neocomplete#complete_common_string()

            " Recommended key-mappings.
            " <CR>: close popup and save indent.
            inoremap <silent> <CR> <C-r>=<SID>my_cr_function()<CR>
            function! s:my_cr_function()
              return (pumvisible() ? "\<C-y>" : "" ) . "\<CR>"
              " For no inserting <CR> key.
              "return pumvisible() ? "\<C-y>" : "\<CR>"
            endfunction
            " <TAB>: completion.
            inoremap <expr><TAB>  pumvisible() ? "\<C-n>" : "\<TAB>"
            " <C-h>, <BS>: close popup and delete backword char.
            inoremap <expr><C-h> neocomplete#smart_close_popup()."\<C-h>"
            inoremap <expr><BS> neocomplete#smart_close_popup()."\<C-h>"
            " Close popup by <Space>.
            "inoremap <expr><Space> pumvisible() ? "\<C-y>" : "\<Space>"

            " AutoComplPop like behavior.
            "let g:neocomplete#enable_auto_select = 1

            " Shell like behavior(not recommended).
            "set completeopt+=longest
            "let g:neocomplete#enable_auto_select = 1
            "let g:neocomplete#disable_auto_complete = 1
            "inoremap <expr><TAB>  pumvisible() ? "\<Down>" : "\<C-x>\<C-u>"

            " Enable omni completion.
            autocmd FileType css setlocal omnifunc=csscomplete#CompleteCSS
            autocmd FileType html,markdown setlocal omnifunc=htmlcomplete#CompleteTags
            autocmd FileType javascript setlocal omnifunc=javascriptcomplete#CompleteJS
            autocmd FileType python setlocal omnifunc=pythoncomplete#Complete
            autocmd FileType xml setlocal omnifunc=xmlcomplete#CompleteTags

            " Enable heavy omni completion.
            if !exists('g:neocomplete#sources#omni#input_patterns')
              let g:neocomplete#sources#omni#input_patterns = {}
            endif
            let g:neocomplete#sources#omni#input_patterns.php = '[^. \t]->\h\w*\|\h\w*::'
            "let g:neocomplete#sources#omni#input_patterns.c = '[^.[:digit:] *\t]\%(\.\|->\)'
            "let g:neocomplete#sources#omni#input_patterns.cpp = '[^.[:digit:] *\t]\%(\.\|->\)\|\h\w*::'

            " For perlomni.vim setting.
            " https://github.com/c9s/perlomni.vim
            "let g:neocomplete#sources#omni#input_patterns.perl = '\h\w*->\h\w*\|\h\w*::'
        endif
    "Plugin 'Raimondi/delimitMate'  " 1) 缺点：打乱了undo history， 用于补全括号和引号
    "Plugin 'tpope/vim-surround'    " 2) 缺点：打乱了undo history， 快速的删除、修改和添加 括号、引号、XML标签等等
    Plugin 'kshenoy/vim-signature'  " toggle, display and navigate marks
    " project 
    "Plugin 'vim-scripts/DfrankUtil'         " Vimprj need
    " TODO has problem stat("///////////////.vimprj"
    "Plugin 'vim-scripts/vimprj'             " managing options for different projects   http://dmitryfrank.com/articles/vim_project_code_navigation
    "Plugin 'vim-scripts/indexer.tar.gz'     " indexing all files in project with ctags
    Plugin 'majutsushi/tagbar'              " displays tags in a window, ordered by scope. It only creates the tags it needs on-the-fly in-memory without creating any files. tags
    Plugin 'vim-scripts/bufexplorer.zip'    " Buffer Explorer / Browser
    Plugin 'scrooloose/nerdtree'            " A tree explorer plugin
    " language
    Plugin 'vim-scripts/Emmet.vim'      " vim plugins for HTML and CSS hi-speed coding.
    Plugin 'vim-scripts/jsbeautify'     " a javascript source code formatter
    "Plugin 'YouCompleteMe'
    Plugin 'vim-scripts/pythoncomplete' " Python Omni Completion
        "autocmd FileType python set omnifunc=pythoncomplete#Complete
        "autocmd FileType php set omnifunc=phpcomplete#CompletePHP

    " 2) plugin from http://vim-scripts.org/vim/scripts.html
    " -- Plugin 'L9'
    Plugin 'Solarized'          " https://github.com/vim-scripts/Solarized http://ethanschoonover.com/solarized         Beautiful dual light/dark, selective contrast, GUI/256/16 colorscheme
        "set background=dark "有dark和light两种可选
        "colorscheme solarized
    Plugin 'a.vim'              " Alternate Files quickly (.c --> .h etc)
    Plugin 'Align'              " 1) 对齐，align text, eqns, declarations, tables, etc  http://www.drchip.org/astronaut/vim/align.html#Examples
    Plugin 'godlygeek/tabular'  " 2) 对齐，text filtering and alignment
        if exists(":Tabularize")
          nmap <Leader>a= :Tabularize /=<CR>
          vmap <Leader>a= :Tabularize /=<CR>
          nmap <Leader>a: :Tabularize /:\zs<CR>
          vmap <Leader>a: :Tabularize /:\zs<CR>
        endif
    Plugin 'DrawIt'             " https://github.com/vim-scripts/DrawIt         Ascii drawing plugin: lines, ellipses, arrows, fills, and more
    "Plugin 'Indent-Guides'         " https://github.com/vim-scripts/Indent-Guides      A plugin for visually displaying indent levels in gvim
    Plugin 'sjl/gundo.vim.git'      " https://github.com/sjl/gundo.vim          Visualize your undo tree.
        let g:gundo_prefer_python3=1
        nnoremap <Leader>u :GundoToggle<CR>
    Plugin 'clwu88/DoxygenToolkit.vim'     " https://github.com/vim-scripts/DoxygenToolkit.vim Simplify Doxygen documentation in C, C++, Python
        let g:DoxygenToolkit_authorName="clwu"
        let g:DoxygenToolkit_licenseTag="private license\<enter>"
        let g:DoxygenToolkit_undocTag="DOXIGEN_SKIP_BLOCK"
        let g:DoxygenToolkit_briefTag_pre = ""
        let g:DoxygenToolkit_paramTag_pre = "@param\t"
        let g:DoxygenToolkit_returnTag = "@return\t"
        let g:DoxygenToolkit_briefTag_funcName = "no"
        let g:DoxygenToolkit_maxFunctionProtoLines = 30
    Plugin 'todo-vim'           " https://github.com/vim-scripts/todo-vim       todo-vim is plugin for manage your todo notes
    Plugin 'rainbow_parentheses.vim'    " https://github.com/vim-scripts/rainbow_parentheses.vim    Rainbow Parentheses
        " Commands:
        "     :RainbowParenthesesToggle       " Toggle it on/off
        "     :RainbowParenthesesLoadRound    " (), the default when toggling
        "     :RainbowParenthesesLoadSquare   " []
        "     :RainbowParenthesesLoadBraces   " {}
        "     :RainbowParenthesesLoadChevrons " <>
        " Always On:
        "     au VimEnter * RainbowParenthesesToggle
        "     au Syntax * RainbowParenthesesLoadRound
        "     au Syntax * RainbowParenthesesLoadSquare
        "     au Syntax * RainbowParenthesesLoadBraces
        nmap \( :RainbowParenthesesToggle<CR>
    "Plugin 'CCTree'            " https://github.com/vim-scripts/CCTree         C Call-Tree Explorer - Source-code analysis, real-time display of code flow
    "Plugin 'TagHighlight'          " https://github.com/vim-scripts/TagHighlight       Extra highlighting of typedefs, enumerations etc (based on ctags)
    "Plugin 'code_complete'         " https://github.com/vim-scripts/code_complete      function parameter complete, code snippets, and much more
        "   Use the command below to create tags file including signature field.     
        "   ctags -R --c-kinds=+p --fields=+S .
        "set tags+=/usr/include/tags
        "set tags+=~/.vim/systags
        "set tags+=~/.vim/glibc_g++.tags
    "Plugin 'a'             " https://github.com/vim-scripts/a.vim          Alternate Files quickly (.c --> .h etc)
    "Plugin 'Tagbar'            " https://github.com/vim-scripts/Tagbar         Display tags of the current file ordered by scope
    "Plugin 'surround'          " https://github.com/vim-scripts/surround.vim       Delete/change/add parentheses/quotes/XML-tags/much more with ease
    "Plugin 'autoproto.vim'         " http://www.vim.org/scripts/script.php?script_id=1553          Auto display function parameter in preview 
        "   - for your project: ":!ctags -R ." (or use the gvim button) 
        "   - for library functions: 
        "     run: "ctags -R -f ~/.vim/systags --c-kinds=+p /usr/include /usr/local/include" 
        "joshua:/usr/include$ sudo ctags -L tags.file --c-kinds=+p --fields=+S -I "__THROW __nonnull __attribute_pure__ __attribute__ G_GNUC_PRINTF+ __wur"
        "     put  "set tags+=~/.vim/systags" in your .vimrc file. 
    "Plugin 'cscope_dynamic'        " https://github.com/vim-scripts/cscope_dynamic     Quick dynamic cscope updates
    "Plugin 'nerdtree'
        "map <F8> :NERDTreeToggle .<CR>
    "Plugin 'nerdtree-git-plugin'
    Plugin 'scrooloose/nerdcommenter'           " Comment functions     https://github.com/scrooloose/nerdcommenter
        " Add spaces after comment delimiters by default
        let g:NERDSpaceDelims = 1
        " Use compact syntax for prettified multi-line comments
        let g:NERDCompactSexyComs = 1
        " Align line-wise comment delimiters flush left instead of following code indentation
        let g:NERDDefaultAlign = 'left'
        " Set a language to use its alternate delimiters by default
        let g:NERDAltDelims_java = 1
        " Add your own custom formats or override the defaults
        let g:NERDCustomDelimiters = { 'c': { 'left': '/**','right': '*/' } }
        " Allow commenting and inverting empty lines (useful when commenting a region)
        let g:NERDCommentEmptyLines = 1
        " Enable trimming of trailing whitespace when uncommenting
        let g:NERDTrimTrailingWhitespace = 1
        " 使用：  
        " 1、 \cc 注释当前行和选中行  
        " 2、 \cn 没有发现和\cc有区别  
        " 3、 \c<空格> 如果被选区域有部分被注释，则对被选区域执行取消注释操作，其它情况执行反转注释操作  
        " 4、 \cm 对被选区域用一对注释符进行注释，前面的注释对每一行都会添加注释  
        " 5、 \ci 执行反转注释操作，选中区域注释部分取消注释，非注释部分添加注释  
        " 6、 \cs 添加性感的注释，代码开头介绍部分通常使用该注释  
        " 7、 \cy 添加注释，并复制被添加注释的部分  
        " 8、 \c$ 注释当前光标到改行结尾的内容  
        " 9、 \cA 跳转到该行结尾添加注释，并进入编辑模式  
        " 10、\ca 转换注释的方式，比如： /**/和//  
        " 11、\cl \cb 左对齐和左右对其，左右对其主要针对/**/  
        " 12、\cu 取消注释  
    Plugin 'dbext.vim'          " https://github.com/vim-scripts/dbext.vim      Provides database access to many dbms (Oracle, Sybase, Microsoft, MySQL, DBI,..)
    "Plugin 'session ???'       vim-scripts/gsession.vim vim-scripts/autosession.vim edsono/vim-sessions 

    Plugin 'mattn/emmet-vim'    " improves HTML & CSS workflow
    " Plugin 'altercation/vim-colors-solarized'    " precision colorscheme for the vim text editor http://ethanschoonover.com/solarized
        " syntax enable
        " set background=dark
        " colorscheme solarized
        " or, for the light background mode of Solarized:
        " syntax enable
        " set background=light
        " colorscheme solarized

    " 3) Git plugin not hosted on GitHub
    " -- Plugin 'git://git.wincent.com/command-t.git'
    Plugin 'https://git.oschina.net/clwu/vim_colorscheme_clwu.git'
    Plugin 'https://git.oschina.net/clwu/vim_misc_tools.git'
    Plugin 'https://git.oschina.net/clwu/vim_mark_clwu.git'         " Highlight several words in different colors simultaneously. (#1238 continued) 
        " 鼠标双击高亮
        map <2-leftmouse> <Leader>m
    Plugin 'https://git.oschina.net/clwu/vimcdoc.git'   " http://vimcdoc.sourceforge.net/   Vim online documentation Chinese version

    " 4) git repos on your local machine (i.e. when working on your own plugin)
    " -- Plugin 'file:///home/gmarik/path/to/plugin'

    " -- " The sparkup vim script is in a subdirectory of this repo called vim.
    " -- " Pass the path to set the runtimepath properly.
    " -- Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
    " -- " Install L9 and avoid a Naming conflict if you've already installed a
    " -- " different version somewhere else.
    " -- Plugin 'ascenator/L9', {'name': 'newL9'}

    " All of your Plugins must be added before the following line

    " statusline 可能会配置成 依赖别的插件，所在放在最后来配置
    Plugin 'itchyny/lightline.vim'      " statusline
    let g:lightline = {
          \    'colorscheme': 'jellybeans',
          \    'active': {
          \      'left': [ [ 'mode', 'paste' ],
          \                [ 'gitbranch', 'readonly', 'gitfilename', 'modified', 'gutentags_status' ] ],
          \      'right': [ [ 'mylineinfo' ],
          \                 [ 'percent' ],
          \                 [ 'myfileformat', 'myfileencoding', 'filetype' ] ],
          \    },
          \    'component': {
          \      'mylineinfo': '%3v,%n',
          \      'myfileencoding': '%{toupper(&fenc!=#""?&fenc:&enc).((exists("+bomb") && &bomb)?",BOM":"")}',
          \      'myfileformat': '%{toupper(&ff)}',
          \      'gitfilename': '%<%{substitute(expand("%:p"), substitute(FugitiveGitDir(), ".git", "", ""), "", "")}',
          \    },
          \    'component_function': {
          \      'gitbranch': 'fugitive#head',
          \      'gutentags_status': 'gutentags#statusline',
          \    },
          \ }
    let g:lightline.inactive = g:lightline.active
call vundle#end()            " required

filetype plugin indent on    " required
" To ignore plugin indent changes, instead use:
"filetype plugin on
"
" Brief help
" :PluginList       - lists configured plugins
" :PluginInstall    - installs plugins; append `!` to update or just :PluginUpdate
" :PluginSearch foo - searches for foo; append `!` to refresh local cache
" :PluginClean      - confirms removal of unused plugins; append `!` to auto-approve removal
"
" see :h vundle for more details or wiki for FAQ
" Put your non-Plugin stuff after this line

" =========================== Vundle Configure End ===========================

" 去掉输入错误的提示声音
set noeb
" 增强模式中的命令行自动完成操作
set wildmenu
" 设定保存历史记录的行数
set history=500
" 不回绕，no [search hit BOTTOM without match]
set nowrapscan

" ============================== untest ============================
" http://www.oschina.net/code/snippet_119181_4840
set shortmess=aItToO   " 去掉欢迎界面 bug: git d比较文件时会提示 Press ENTER or type command to continue
set magic           " It is recommended to always keep the 'magic' option at the default setting, which is 'magic'.  This avoids portability problems.
" 不使用beep或flash 
set vb t_vb=
" 根据给定方向搜索当前光标下的单词，结合下面两个绑定使用
function! VisualSearch(direction) range
    let l:saved_reg = @"
    execute "normal! vgvy"
    let l:pattern = escape(@", '\\/.*$^~[]')
    let l:pattern = substitute(l:pattern, "\n$", "", "")
    if a:direction == 'b'
        execute "normal ?" . l:pattern . "<cr>"
    else
        execute "normal /" . l:pattern . "<cr>"
    endif
    let @/ = l:pattern
    let @" = l:saved_reg
endfunction
" 用 */# 向 前/后 搜索光标下的单词
vnoremap <silent> * :call VisualSearch('f')<CR>
vnoremap <silent> # :call VisualSearch('b')<CR>

"从系统剪切板中复制，剪切，粘贴
"map <F7> "+y
"map <F8> "+x
"map <F9> "+p

" 在文件名上按gf时，在新的tab中打开
map gf :tabnew <cfile><cr>
" 恢复上次文件打开位置
"set viminfo='10,\"100,:20,%,n~/.viminfo
"au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif

" project, Command Completion
" http://www.phpbuilder.com/columns/vim/Jason_Gilmore092210.php3?page=2
" ==================================================================

set t_Co=256

"colorscheme wombat256
colorscheme clwu

set nu
" toggle between absolute number and relative number
function! <SID>ToggleNumber()
    if !&relativenumber
        set relativenumber
    else
        set norelativenumber
    endif
endfunc
nmap \r :call <SID>ToggleNumber()<CR>

if !isdirectory('/tmp/vim-backup/') " 没有这个目录就创建
    call mkdir('/tmp/vim-backup', '', 0777)
    call system("chmod a+w /tmp/vim-backup") " umask
endif
set backupdir=/tmp/vim-backup
set nobackup

set tabstop=4        " 按tab时变成4个空格
set shiftwidth=4     " 4个空格缩进
set scrolloff=5      " " 光标移动到buffer的顶部和底部时保持5行距离
"set softtabstop=4   " 将4个空格当作一个tab来处理
"set expandtab       " retab
"设置出缩进提示线
se list 
"se nolist 
"se lcs=tab:>- 
set lcs=tab:\|\ 
hi SpecialKey guifg=#333333

autocmd FileType c,cpp,cuda,php,java,javascript set cindent | set cinoptions=:0,l1,g0,t0,(0,w1,J1
                       \ | set expandtab | set softtabstop=4 | set backup " 按tab 时使用空格
"autocmd FileType c,cpp run macros/gdb_mappings.vim
autocmd FileType python,markdown,vim set expandtab | set softtabstop=4 | set backup " 按tab 时使用空格

" Recognize standard C++ headers
au BufEnter /usr/include/**    setf cpp | set tabstop=8 | set nobackup | set readonly

" Setting for files following the GNU coding standard
"au BufEnter /usr/*                call GnuIndent()

" 用空格键来开关折叠
"set foldenable
function! <SID>ToggleFoldMethod()
    if &fdm == 'manual'
        setlocal fdm=indent
    else
        setlocal fdm=manual
    endif
endfunc
nmap \<space> :call <SID>ToggleFoldMethod()<CR>
nnoremap <space> @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')<CR>

"if ! has("gdb")
"   set nonu
"endif

set encoding=utf-8 fileencodings=utf-8,cp936,ucs-bom,default,latin1
"set fileencodings+=cp936

" Unfortunately, when this option is set some plugins may not work correctly if they make assumptions about the current directory.
"autocmd BufEnter * lcd %:p:h
" FIX lcd problem in Session.vim
" 修复 与fugitive的冲突
let g:inMySession_vim = 0
autocmd BufEnter * if (!g:inMySession_vim) | silent! lcd %:p:h | endif


if has("statusline")
set laststatus=2
" 停用，因为用了插件 lightline
"set statusline=%{fugitive#statusline()}%F%m%r%h%w\ %=[FORMAT=%{&ff}]\ %{\"[\".(&fenc==\"\"?&enc:&fenc).((exists(\"+bomb\")\ &&\ &bomb)?\",B\":\"\").\"]\"}[TYPE=%Y][%p%%,%3v,%n]
endif

"It is often useful to restrict the range of commands like s or g to 
"the function one is currently editing. For C/C++ and Java,
cmap ;tf ?^{??(?,/^}/

" csindent plugin --------------------------------------------------------
"let g:csindent_ini='~/.vim/vim_csindent.ini'

" quickfix window
"au FileType qf setlocal nonumber colorcolumn=

autocmd BufNewFile *.[ch],*.hpp,*.cpp,*.sh,*.java,*.js,*.py exec ":call SetTitle()" 
"加入注释
func SetComment()
    call setline(1,          "/*===============================================================") 
    call append(line("."),   "*   Copyright (C) ".strftime("%Y")." All rights reserved.")
    call append(line(".")+1, "*   ") 
    call append(line(".")+2, "*   file     : ".expand("%:t")) 
    call append(line(".")+3, "*   author   : clwu")
    call append(line(".")+4, "*   date     : ".strftime("%Y-%m-%d")) 
    call append(line(".")+5, "*   descripe : ") 
    call append(line(".")+6, "*")
    call append(line(".")+7, "*   modify   : ") 
    call append(line(".")+8, "*") 
    call append(line(".")+9, "================================================================*/") 
endfunc

"定义函数SetTitle，自动插入文件头 
func SetTitle()
    "如果文件类型为.sh文件 
    if &filetype == 'sh' 
        call setline(1,"\#!/bin/bash") 
        call append(line("."), "") 
    elseif &filetype == 'python'
        call setline(1,"#!/usr/bin/env python3")
        " call append(line("."),"# coding=utf-8")
        call append(line(".")+1, "")
    else
        call SetComment()
    endif

    if &filetype == 'java'
        call append(line(".")+10,"public class ".expand("%:r"))
        call append(line(".")+11,"")
    elseif expand("%:e") == 'hpp' 
        call append(line(".")+10, "#ifndef _".toupper(substitute(expand("%:t:r"), "[^[:alnum:]]", "_", "g")."_H"))  
        call append(line(".")+11, "#define _".toupper(substitute(expand("%:t:r"), "[^[:alnum:]]", "_", "g")."_H"))  
        call append(line(".")+12, "#ifdef __cplusplus") 
        call append(line(".")+13, "extern \"C\"") 
        call append(line(".")+14, "{") 
        call append(line(".")+15, "#endif") 
        call append(line(".")+16, "") 
        call append(line(".")+17, "#ifdef __cplusplus") 
        call append(line(".")+18, "}") 
        call append(line(".")+19, "#endif") 
        call append(line(".")+20, "#endif // _".toupper(substitute(expand("%:t:r"), "[^[:alnum:]]", "_", "g")."_H"))
    elseif expand("%:e") == 'h'
        call append(line(".")+10, "#ifndef _".toupper(substitute(expand("%:t:r"), "[^[:alnum:]]", "_", "g")."_H"))  
        call append(line(".")+11, "#define _".toupper(substitute(expand("%:t:r"), "[^[:alnum:]]", "_", "g")."_H"))  
        call append(line(".")+12, "") 
        call append(line(".")+13, "#endif // _".toupper(substitute(expand("%:t:r"), "[^[:alnum:]]", "_", "g")."_H"))  
    elseif &filetype == 'c' 
        call append(line(".")+10,"#include \"".expand("%:t:r").".h\"") 
    elseif &filetype == 'cpp' 
        call append(line(".")+10, "#include \"".expand("%:t:r").".h\"") 
        call append(line(".")+11, "using namespace std;")
        call append(line(".")+12, "")
    endif
    call append(line("$"), "") 
    call append(line("$"), "") 
    call append(line("$"), "") 
    " 模式行 modeline | usr_21.txt
    if &filetype == 'python'
        call append(line("$"), "# vim: set nu expandtab softtabstop=4 tabstop=4 tw=80:") 
    else
        call append(line("$"), "/* vim: set nu expandtab softtabstop=4 tabstop=4 tw=80: */") 
    endif
endfunc

""C，C++ 按F5编译运行
"map <F5> :call CompileRunGcc()<CR>
"func! CompileRunGcc()
"    exec "w"
"    if &filetype == 'c'
"        exec "!g++ % -o %<"
"        exec "!time ./%<"
"    elseif &filetype == 'cpp'
"        exec "!g++ % -o %<"
"        exec "!time ./%<"
"    elseif &filetype == 'java' 
"        exec "!javac %" 
"        exec "!time java %<"
"    elseif &filetype == 'sh'
"        :!time bash %
"    elseif &filetype == 'python'
"        exec "!time python2.7 %"
"    elseif &filetype == 'html'
"        exec "!firefox % &"
"    elseif &filetype == 'go'
"        "        exec "!go build %<"
"        exec "!time go run %"
"    elseif &filetype == 'mkd'
"        exec "!~/.vim/markdown.pl % > %.html &"
"        exec "!firefox %.html &"
"    endif
"endfunc
""C,C++的调试
"map <F8> :call Rungdb()<CR>
"func! Rungdb()
"    exec "w"
"    exec "!g++ % -g -o %<"
"    exec "!gdb ./%<"
"endfunc


""代码格式优化化
"map <F6> :call FormartSrc()<CR><CR>
""定义FormartSrc()
"func FormartSrc()
"    exec "w"
"    if &filetype == 'c'
"        exec "!astyle --style=ansi -a --suffix=none %"
"    elseif &filetype == 'cpp' || &filetype == 'hpp'
"        exec "r !astyle --style=ansi --one-line=keep-statements -a --suffix=none %> /dev/null 2>&1"
"    elseif &filetype == 'perl'
"        exec "!astyle --style=gnu --suffix=none %"
"    elseif &filetype == 'py'||&filetype == 'python'
"        exec "r !autopep8 -i --aggressive %"
"    elseif &filetype == 'java' ||&filetype == 'php'
"        exec "!astyle --style=java --suffix=none %"
"    elseif &filetype == 'jsp'
"        exec "!astyle --style=gnu --suffix=none %"
"    elseif &filetype == 'xml'
"        exec "!astyle --style=gnu --suffix=none %"
"    else
"        exec "normal gg=G"
"        return
"    endif
"    exec "e! %"
"endfunc
""结束定义FormartSrc


" Show syntax highlighting groups for word under cursor
nmap <C-S-J> :call <SID>SynStack()<CR>
function! <SID>SynStack()
  if !exists("*synstack")
    return
  endif
  echo map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")')
endfunc


"=========================================================

if has("autocmd")
    filetype plugin indent on "根据文件进行缩进
    augroup vimrcEx
        " 删除当前组里_所有_的自动命令。
        au!
        autocmd FileType text setlocal textwidth=78
        autocmd BufReadPost *
                    \ if line("'\"") > 1 && line("'\"") <= line("$") |
                    \ exe "normal! g`\"" |
                    \ endif
    augroup END
else
    "智能缩进，相应的有cindent，官方说autoindent可以支持各种文件的缩进，但是效果会比只支持C/C++的cindent效果会差一点，但笔者并没有看出来
    set autoindent " always set autoindenting on 
endif " has("autocmd")
set tabstop=4 "让一个tab等于4个空格
set vb t_vb=
set nowrap "不自动换行

set hlsearch "高亮显示结果
" an easy way to turn off all the highlighted matches when you’re done with them
nmap <silent> <BS>  :nohlsearch<CR>

" set wrapscan
set incsearch "在输入要搜索的文字时，vim会实时匹配
set backspace=indent,eol,start whichwrap+=<,>,[,] "允许退格键的使用
if(g:iswindows==1) "允许鼠标的使用
    "防止linux终端下无法拷贝
    if has('mouse')
        set mouse=a
    endif
    au GUIEnter * simalt ~x
endif
"字体的设置
"set guifont=Bitstream_Vera_Sans_Mono:h9:cANSI "记住空格用下划线代替哦
"set gfw=幼圆:h10:cGB2312
set guioptions=aegimt

if filereadable("cscope.out")
    execute "cs add cscope.out"
endif
set tagstack

" ctags 生成系统头文件时对GCC定义的宏处理不正确
" ctags -I "__THROW __nonnull __attribute_pure__ __attribute__ G_GNUC_PRINTF+ __wur" \
"     --c++-kinds=+px --c-kinds=+px --fields=+iaS -a -f tags --extra=+fq --langmap=c:+.h \
"     --languages=c,c++ --c-kinds=+px --c++-kinds=+px -L $tmpfilename 

"set cscopequickfix=s-,c-,d-,i-,t-,e-
"nmap <F12> :call Do_CsTag()<CR>
nmap <C-@>s :split\|cs find s <C-R>=expand("<cword>")<CR><CR>
nmap <C-@>g :split\|cs find g <C-R>=expand("<cword>")<CR><CR>
nmap <C-@>c :split\|cs find c <C-R>=expand("<cword>")<CR><CR>
nmap <C-@>t :split\|cs find t <C-R>=expand("<cword>")<CR><CR>
nmap <C-@>e :split\|cs find e <C-R>=expand("<cword>")<CR><CR>
nmap <C-@>f :split\|cs find f <C-R>=expand("<cfile>")<CR><CR>
nmap <C-@>i :split\|cs find i ^<C-R>=expand("<cfile>")<CR>$<CR>:copen<CR>
nmap <C-@>d :split\|cs find d <C-R>=expand("<cword>")<CR><CR>
function Do_CsTag()
    let dir = getcwd()
    if filereadable("tags")
        if(g:iswindows==1)
            let tagsdeleted=delete(dir."\\"."tags")
        else
            let tagsdeleted=delete("./"."tags")
        endif
        if(tagsdeleted!=0)
            echohl WarningMsg | echo "Fail to do tags! I cannot delete the tags" | echohl None
            return
        endif
    endif
    if has("cscope")
        silent! execute "cs kill -1"
    endif
    if filereadable("cscope.files")
        if(g:iswindows==1)
            let csfilesdeleted=delete(dir."\\"."cscope.files")
        else
            let csfilesdeleted=delete("./"."cscope.files")
        endif
        if(csfilesdeleted!=0)
            echohl WarningMsg | echo "Fail to do cscope! I cannot delete the cscope.files" | echohl None
            return
        endif
    endif
    if filereadable("cscope.out")
        if(g:iswindows==1)
            let csoutdeleted=delete(dir."\\"."cscope.out")
        else
            let csoutdeleted=delete("./"."cscope.out")
        endif
        if(csoutdeleted!=0)
            echohl WarningMsg | echo "Fail to do cscope! I cannot delete the cscope.out" | echohl None
            return
        endif
    endif
    if(executable('ctags'))
        "silent! execute "!ctags -R --c-types=+p --fields=+S *"
        silent! execute "!ctags -R --c++-kinds=+p --fields=+iaS --extra=+q ."
    endif
    if(executable('cscope') && has("cscope") )
        if(g:iswindows!=1)
            silent! execute "!find . -name '*.h' -o -name '*.c' -o -name '*.cpp' -o -name '*.java' -o -name '*.cs' > cscope.files"
        else
            silent! execute "!dir /s/b *.c,*.cpp,*.h,*.java,*.cs >> cscope.files"
        endif
        silent! execute "!cscope -b"
        execute "normal :"
        if filereadable("cscope.out")
            execute "cs add cscope.out"
        endif
    endif
endfunction

" when in a project dir (dir path contain keyword *project*), 
" try to load project self definition or specific configuration -- project.vim
function LoadProjectCfg()
    let olddir = getcwd().'/'
    let dirlist = split(olddir, '/\zs')
    let idx = index(dirlist, "project/")
    let len = len(dirlist)
    let i = len - 1
        " findfile() ???
    if idx > 0
        while i >= idx
            let dir = join(dirlist[0:i], '')
            if filereadable(dir."_project.vim")
                let g:myProjectArg_dir = dir
                exec "source ".dir."_project.vim"
                " comment the break line will exec each project.vim under subdir
                break
            else
                let i -= 1
            endif
        endwhile
        unlet! g:myProjectArg_dir
    endif
endfunction
" silent! call LoadProjectCfg()


" {{{全文搜索选中的文字
:vmap <silent> <leader>f y/<C-R>=escape(@", '\\/.*$^~[]')<CR><CR>
:vmap <silent> <leader>F y?<C-R>=escape(@", '\\/.*$^~[]')<CR><CR>
" }}}


"omnicppcomplete会打开一个预览窗口来提示变量定义，如果不想要看到详细的信息的话 set completeopt=menu
set completeopt=menu


"有时候我们想看一下几行的字符是不是在同一列上时，按下,ch 就可以将当前光标下的列高亮，再按下一次，取消高亮；并且可以同时多列高亮
map ,ch :call SetColorColumn()<CR>
function! SetColorColumn()
    let col_num = virtcol(".")
    let cc_list = split(&cc, ',')
    if count(cc_list, string(col_num)) <= 0
        execute "set cc+=".col_num
    else
        execute "set cc-=".col_num
    endif
endfunction


" {{{ 手工格式化缩进代码，调用indent
" %r !cat % | indent -l80 -i4 -ts4 -nut -bli0 -br -bs -ce -cli0 -cbi0 -ncs -il0 -bbo -cdw -npcs -saf -saw -sbi0 -bls -blf -hnl -st
function <SID>clwu_Indent_C() range
    let pnr = cindent(a:firstline)
    let linelen = 80 - pnr
    let linelen = (linelen > 0) ? linelen : 80

    if &filetype == 'php'
        let cmd = a:firstline.','.a:lastline.'!astyle --style=java --lineend=linux --add-brackets --indent-namespaces --pad-header --pad-oper --suffix=none -M120 2>/dev/null'
    else
        let cmd = a:firstline.','.a:lastline.'!indent -l'.linelen.' -i4 -ts4 -nut -bli0 -br -bs -ce -cli0 -cbi0 -ncs -il0 -bbo -cdw -npcs -saf -saw -sbi0 -bls -blf -hnl -st 2>/dev/null'
    endif

    let before = line('$')
    execute cmd
    let incr = line('$') - before " 行数可能会增加/减少，需要重新计算
    execute 'normal '.a:firstline.'G'.(a:lastline-a:firstline+1+incr).'=='
endfunction
nmap \f :call <SID>clwu_Indent_C()<CR><CR>
" }}}

" {{{ 列对齐格式化缩进代码
function <SID>column_code() range
    let cmd = a:firstline.','.a:lastline.'!column -t -o" "'
    execute cmd
    execute 'normal '.a:firstline.'G'.(a:lastline-a:firstline+1).'=='
endfunction
nmap \c :call <SID>column_code()<CR><CR>
" }}}

" {{{ toggle wrap
function <SID>toggle_wrap()
    if &wrap
        execute 'setlocal nowrap'
    else
        execute 'setlocal wrap'
    endif
endfunction
nmap \w :call <SID>toggle_wrap()<CR><CR>
" }}}

" []、{}、()、""、' '等自动补全
:inoremap ( ()<ESC>i
:inoremap ) <c-r>=ClosePair(')')<CR>
:inoremap { {<CR>}<ESC>O
:inoremap } <c-r>=ClosePair('}')<CR>
:inoremap [ []<ESC>i
:inoremap ] <c-r>=ClosePair(']')<CR>
:inoremap " ""<ESC>i
:inoremap ' ''<ESC>i
function! ClosePair(char)
    if getline('.')[col('.') - 1] == a:char
        return "\<Right>"
    else
        return a:char
    endif
endfunction

" Tab navigation like Firefox.
nnoremap <C-S-Tab> :tabprevious<CR>
nnoremap <C-Tab>   :tabnext<CR>
"inoremap <C-S-Tab> <Esc>:tabprevious<CR>i
"inoremap <C-Tab>   <Esc>:tabnext<CR>i
inoremap <C-S-Tab> <Esc>:tabprevious<CR>
inoremap <C-Tab>   <Esc>:tabnext<CR>
nnoremap <C-Enter>   :tabnew<CR>
inoremap <C-Enter>   <Esc>:tabnew<CR>
nnoremap <C-BS>   :tabclose<CR>
inoremap <C-BS>   <Esc>:tabclose<CR>
nnoremap <C-S-BS>   :tabonly<CR>
inoremap <C-S-BS>   <Esc>:tabonly<CR>

" 这个是由于git自身造成的 它会解决冲突后 生成一个原来冲突的备份，我们可以去掉
" git config --global mergetool.keepBackup false

" 如何使用 vimdiff 来 git diff
" ============================
" 1 Set up vimdiff
" ---------------
"   git config --global diff.tool vimdiff  
"   git config --global difftool.prompt false  
"   git config --global alias.d difftool  
    map <silent> <leader>1 :diffget 1<CR> :diffupdate<CR>
    map <silent> <leader>2 :diffget 2<CR> :diffupdate<CR>
    map <silent> <leader>3 :diffget 3<CR> :diffupdate<CR>
    map <silent> <leader>4 :diffget 4<CR> :diffupdate<CR>
" 2 Set up git
" ------------
" To use vimdiff as default merge tool:
"   git config --global merge.tool vimdiff
"   git config --global mergetool.prompt false
"   如果不加具体的文件，默认的是一个一个的比对文件，使用:qa退出单个文件，如果想使用:cq退出整个比对，需要增加如下参数
"   git config --global difftool.trustExitCode true
" :map <C-X> <ESC>:qa<CR>
" :imap <C-X> <ESC>:qa<CR>


":se[t] inv{option}	切换选项: 反转其值。{Vi 无此功能}
nmap \p :set invpaste<CR> 

" Allow saving of files as sudo when I forgot to start vim using sudo.
cmap w!! w !sudo tee > /dev/null %

" ========= auto save and load :mksession =========
let s:sessiondir = $HOME . "/.vim/_sessions/" 
let s:session_name = s:sessiondir . substitute(getcwd(), "/", "_", "g") . '.vim'
function s:MakeSession()
  if (filewritable(s:sessiondir) != 2)
    exe 'silent !mkdir -p ' s:sessiondir
    redraw!
  endif
  exe "mksession! " . s:session_name
endfunction

function s:LoadSession()
  if (filereadable(s:session_name))
    exe 'source ' s:session_name
  endif
endfunction

" 防止误提交了 git 合并冲突的标记，它们高亮出来以免错过了
match ErrorMsg '^\(<\|=\|>\)\{7\}\([^=].\+\)\?$'

syntax on "打开高亮
" set redrawtime=3000
" ==================

" Adding automatons for when entering or leaving Vim
" if(argc() == 0)
"   au VimEnter * :call s:LoadSession()
" endif
" " au VimEnter * :call s:LoadSession()
" au VimLeave * :call s:MakeSession()


" let g:netrw_browsex_viewer= "xdg-open"
let g:netrw_browsex_viewer= "/usr/bin/firefox --private-window" " @see :h gx, netrw plugin


" 围观这个强大Vim配置: https://github.com/liangxianzhe/dotvim
" https://github.com/xolox/vim-easytags
" https://zilongshanren.com/blog/2014-06-19-make-your-vim-weapon.html
" c.vim   *** 　　http://www.vim.org/scripts/script.php?script_id=213 　　提供了很多便于C/C++编程的功能，比如文件头模版，代码片断等。
" CRefVim   ** 　　http://www.vim.org/scripts/script.php?script_id=614 　　为VIM定制的C参考手册，这样对于语法或者函数不清楚的地方可以方便的查找了。
" project 　　http://www.vim.org/scripts/script.php?script_id=69 　　提供一些IDE功能，看介绍似乎很不错。

" https://github.com/yangyangwithgnu/use_vim_as_ide
" http://vim.wikia.com/wiki/Best_Vim_Tips
